<template>
  <div class="header">
    <router-link to="/">
      <div class="header1">
        <span class="iconfont">&#xe685;</span>
      </div>
    </router-link>
    <h1 class="header2">
      城市选择
    </h1>
    <div>
      <div class="search">
       <input type="text" placeholder="输入城市名及拼音" class="search-input" v-model="keyword">
      </div>
      <div class="search-content" ref="search" v-show="keyword">
        <ul>
          <li class="search-item border-bottom"
              v-for="item in list" :key="item.id" @click="handleCityCilck(item.name)">
            {{item.name}}
          </li>
          <li class="search-item border-bottom" v-show="hasNoData">
            没有找到匹配数据
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
export default {
  name: 'CityHeader',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null,
      bindScroll: false
    }
  },
  methods: {
    handleCityCilck (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (this.keyword.length === 0) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 ||
                value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
        this.bindScroll = !this.bindScroll
      }, 300)
    },
    bindScroll () {
      setTimeout(() => {
        this.scroll = new BScroll(this.$refs.search)
      }, 10)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.header
  z-index 3
  font-size: .32rem
  background-color: $bgColor
  color: #fff
  line-height : .88rem
  // height: .88rem
  padding-bottom .1rem
.header1
  width : .64rem
  flota: left
.header2
  font-size: .32rem
  position  absolute
  top 0
  right 45%
  line-height : .64rem
  margin-top : .12rem
.search
  background-color: #fff
  height: .64rem
  width 95%
  margin-left .2rem
  line-height : .64rem
  margin-top : .12rem
  border-radius  .05rem
  color #ccc;
  text-align center
a
  color white
.search-content
  overflow: hidden;
  z-index 1
  position: absolute;
  top: 1.74rem;
  left: 0;
  right: 0;
  bottom: 0;
  background-color #eee
  .search-item
    line-height: .62rem;
    padding-left: .2rem;
    color: #666;
    background: #fff;
</style>
